package sg.edu.nus.iss.vmcs.entity.simuator;

import java.io.IOException;

import sg.edu.nus.iss.vmcs.entity.Brand;
import sg.edu.nus.iss.vmcs.entity.BrandDrink;
import sg.edu.nus.iss.vmcs.entity.BrandDrinkStore;
import sg.edu.nus.iss.vmcs.entity.BrandDrinkStoreItem;
import sg.edu.nus.iss.vmcs.entity.Coin;
import sg.edu.nus.iss.vmcs.entity.StoreItem;
import sg.edu.nus.iss.vmcs.entity.simuator.dao.ISimulatorDrinkBrandDAO;
import sg.edu.nus.iss.vmcs.entity.simuator.dao.impl.SimulatorDrinkBrandDAOImpl;


public class SimulatorDrinkBrandStore extends BrandDrinkStore {

	private String DRINK_PROPERTIES = "source/DrinkPropertyFile.txt";
	private static SimulatorDrinkBrandStore simulatorDrinkBrandStore = null;
	private ISimulatorDrinkBrandDAO iSimulatorDrinkBrandDAO = null;
	
	String nameAttri = "Name";
	String priceAttri = "Price";
	String quantityAttri = "Quantity";
	
	private SimulatorDrinkBrandStore(){
		try {
			iSimulatorDrinkBrandDAO = SimulatorDrinkBrandDAOImpl.getSimulatorDrinkBrandDao(DRINK_PROPERTIES);
			processStore();
		
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
	@Override
	protected void processStore() {
		int noOfItems = iSimulatorDrinkBrandDAO.getNumOfItems();
		System.out.println("Total entries "+noOfItems);
		this.setStoreSize(noOfItems);

		for(int i=1;i<=noOfItems;i++){
			try{
				String name = iSimulatorDrinkBrandDAO.getAttributeValue(nameAttri+i);
				String priceStr = iSimulatorDrinkBrandDAO.getAttributeValue(priceAttri+i);
				String quantityStr = iSimulatorDrinkBrandDAO.getAttributeValue(quantityAttri+i);
				double price = Double.parseDouble(priceStr);
				int quantity = Integer.parseInt(quantityStr);
				BrandDrink storeObject = new BrandDrink(name, ""+i,price);
				StoreItem storeItem = new BrandDrinkStoreItem(storeObject,quantity);
				addItem((i-1), storeItem);
			}catch(Exception e){
				
			}
		}
	}

	public static BrandDrinkStore getInstance() {
		if(simulatorDrinkBrandStore == null){
			simulatorDrinkBrandStore = new SimulatorDrinkBrandStore();
		}
		return simulatorDrinkBrandStore;
	}
	@Override
	public void storeRecords(){
		for (int i = 0; i < size; i++) {
			if (items[i] == null || items[i].getContent() == null)
				continue;
			StoreItem storeItem = items[i];
			Brand coin = (Brand) storeItem.getContent();
			int quantity = storeItem.getQuantity();
			String id = coin.getId();
			
			String name = coin.getName();
			String price = ""+coin.getPrice();
			try {
				iSimulatorDrinkBrandDAO.update(nameAttri+id,name);
				iSimulatorDrinkBrandDAO.update(priceAttri+id,price);
				iSimulatorDrinkBrandDAO.update(quantityAttri+id,""+quantity);
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}            
		}
	}
	public void updateItem(StoreItem object){
		super.updateItem(object);
		storeRecords();
	}
}
